package com.baibei.ebec.user.mine;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.ebec.user.BuildConfig;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.model.BalanceInfo;
import com.baibei.model.InoutFundParam;
import com.baibei.model.PayModeInfo;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.module.InoutFundParamProvider;
import com.baibei.module.RechargeHelper;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.RxObservable;
import com.baibei.ui.AppUI;
import com.baibei.widget.dialog.PayInputPwdDialog;
import com.blankj.utilcode.utils.LogUtils;
import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;
import com.rae.widget.dialog.DialogBuilder;
import com.rae.widget.dialog.IAppDialog;
import com.rae.widget.dialog.IAppDialogClickListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.baibei.module.Constant.SETFUNDPWD_SUCCESS;

/**
 * 个人用户
 * Created by ChenRui on 2017/8/10 0010 14:12.
 */
@Route(path = "/user/minefragment")
public class MinePersonalFragment extends MineFragment implements MineContract.View {

    @BindView(R2.id.tv_valid_amount)
    TextView mTvValidAmount;
    @BindView(R2.id.tv_freez_amount)
    TextView mTvFreezAmount;
    @BindView(R2.id.btn_share)
    TextView btnShare;
    Unbinder unbinder;
    @BindView(R2.id.img_avatar)
    RoundedImageView imgAvatar;
    @BindView(R2.id.message)
    ImageView message;
    @BindView(R2.id.tv_login_tips)
    TextView tvLoginTips;
    private String mTag = "mine";
    private MineContract.Presenter mPresenter;
    private String accessToken;
    private String userId;
    private UserInfo user;

    public static MinePersonalFragment newInstance() {
        return new MinePersonalFragment();
    }

    @BindView(R2.id.tv_mobile)
    TextView mMobileView;

    @BindView(R2.id.tv_balance)
    TextView mBalanceView;

    IUserApi mUserApi;

    @BindView(R2.id.tv_status_certification)
    TextView mTvStatusCertification;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fm_mine_personal;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserApi = ApiFactory.getInstance().getUserApi();
        mPresenter = inject(MineContract.Presenter.class);
        TokenInfo userToken = SessionManager.getDefault().getUserToken();
        user = SessionManager.getDefault().getUser();
        accessToken = userToken.getAccessToken();
        userId = user.getUserId() + "";
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        if (user.getUserPic() != null) {
            Glide.with(getContext()).load(user.getUserPic()).into(imgAvatar);
        }

        tvLoginTips.setText(user.getUserName());

    }

    @Override
    public void onLoginClick() {
        // 个人信息
    }

    @Override
    public void onResume() {
        super.onResume();
        // 加载余额
        updateInfo();
        Bundle arguments = getArguments();
        if (arguments != null) {
            btnShare.performClick();
            setArguments(null);
        }
    }


    /**
     * 更新信息
     */
    private void updateInfo() {
        if (SessionManager.getDefault().isLogin()) {
            //获取余额跟可用余额
            RxObservable.create(mUserApi.getBalanceInfo(), mTag).subscribe(new ApiDefaultObserver<BalanceInfo>() {
                @Override
                protected void onError(String s) {
                    mBalanceView.setText("余额获取失败");
                    ((BasicActivity) getActivity()).logout();
                }

                @Override
                protected void accept(BalanceInfo info) {
                    mBalanceView.setText(Rx.formatPrice(info.getBalance()));
                }
            });
            mPresenter.updateUserInfo();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (mPresenter != null) {
                mPresenter.getIfHasNewMsg(userId, accessToken);
            }
        }
        if (isVisibleToUser && isAdded()) {
            updateInfo();
        }
    }


    @Override
    public void onDestroy() {
        RxObservable.dispose(mTag);
        mPresenter.destroy();
        super.onDestroy();
    }

    /**
     * 充值
     */
    @OnClick(R2.id.btn_recharge)
    public void onRechargeClick() {
        RechargeHelper.toRecharge(getActivity(), this);
    }


    /**
     * 我的体验券
     */
    @OnClick(R2.id.btn_ticket)
    public void onTicketClick() {
        AppRouter.routeToTicket(getContext());
    }

    /**
     * 实名认证
     */
    @OnClick(R2.id.btn_certification)
    public void onCertificationClick() {
        if (mUserInfo == null) {
            AppUI.failed(getContext(), "用户信息还没有准备好，请稍后再试。");
            return;
        }
        // 没有实名认证
        if (mUserInfo.getIsRealName() == 0) {
            AppRouter.routeToNameAuth(getContext());
        } else {
            AppRouter.routeToNameAuthStatus(getContext(), null, null);
        }
    }

    @OnClick(R2.id.btn_help)
    public void onHelperClick() {
        //跳转到帮助中心，网页h5
        AppRouter.routeToWeb(getContext(), "帮助中心", ApiConstant.API_BASE_URL + "help/index.html");
    }


    @Override
    protected void onLoadUserInfo(UserInfo userInfo) {
        super.onLoadUserInfo(userInfo);
        mMobileView.setText(Rx.blockingPhone(userInfo.getMobile()));
        tvLoginTips.setText(userInfo.getUserName());
    }

    /**
     * 提现
     */
    @OnClick(R2.id.btn_withdraw)
    public void onWithdrawClick() {
        UserInfo userInfo = SessionManager.getDefault().getUser();
        if (userInfo == null) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        if (!userInfo.hasSetFundPwd()) {
            //跳转到设置资金密码界面
            AppRouter.routeToSetPayPwd((Activity) getContext());
            return;
        }
        //显示资金密码
        showCheckPayDialog();
    }

    /**
     * 消息中心
     */
    @OnClick(R2.id.message)
    public void onMessageClick() {
        UserInfo userInfo = SessionManager.getDefault().getUser();
        if (userInfo == null) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        message.setImageResource(R.drawable.xiaoxi);
        AppRouter.routeToMessage(getContext());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //设置资金密码成功
        if (resultCode == SETFUNDPWD_SUCCESS) {
            //弹窗校验资金密码
            showCheckPayDialog();
        }
    }


    /**
     * 提现操作
     * 检验资金密码
     */
    private void showCheckPayDialog() {
        PayInputPwdDialog dialog = new PayInputPwdDialog();

        dialog.setOnPayFinishListener(new PayInputPwdDialog.OnPayFinishListener() {
            @Override
            public void OnPayFinishListener(CharSequence text, DialogFragment fragment) {
                String password = text.toString();
                mPresenter.withdraw(password);
                fragment.dismiss();
            }

            @Override
            public void onDismiss() {
            }
        });
        dialog.show(getFragmentManager(), "pay");
    }


    @Override
    public void onCheckFundSuccess(String password, PayModeInfo info) {
        if (info == null) {
            AppUI.failed(getContext(), BuildConfig.DEBUG ? "接口没有返回提现地址数据" : "服务器正忙，请稍后重试");
            return;
        }
        //检验成功
        InoutFundParam param = InoutFundParamProvider.get();
        param.setUrl(info.getPayUrl());
        param.setFundPassword(password);
        AppRouter.routeToWithdraw(getContext(), password, param);
    }

    @Override
    public void onCheckFundFailed(String msg, boolean isLock) {
        //检验资金密码错误，弹出窗口
        DialogBuilder builder = new DialogBuilder(getContext())
                .setMessage(msg).positiveButtonText("忘记密码")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog iAppDialog, int i) {
                        iAppDialog.dismiss();
                        //跳转到重设资金密码
                        AppRouter.routeToResPayPwd((Activity) getContext());
                    }
                });
        //如果不是锁定，显示重新输入按钮
        if (!isLock) {
            builder.negativeButtonText("重新输入").negativeButtonClickListener(new IAppDialogClickListener() {
                @Override
                public void onClick(IAppDialog iAppDialog, int i) {
                    iAppDialog.dismiss();
                    //重新显示
                    showCheckPayDialog();
                }
            });
        }
        builder.show();
    }

    @Override
    public void onNotEnoughWithDraw(String msg) {
        AppUI.failed(getContext(), msg);
    }

    @Override
    public void showLoading() {
        AppUI.loading(getContext());
    }

    @Override
    public void hideLoading() {
        AppUI.dismiss();
    }

    @Override
    public void onUpdateUserInfo(UserInfo userInfo) {
        //是否已实名制
        if (userInfo != null && userInfo.isPassRealNameVerify()) {
            mTvStatusCertification.setText(R.string.realname_hasverify);
        } else {
            mTvStatusCertification.setText(R.string.realname_notyet);
        }
//        LogUtils.e("log116",userInfo.getUserPic());
        Glide.with(getContext()).load(userInfo.getUserPic()).into(imgAvatar);
        tvLoginTips.setText(userInfo.getUserName());
    }

    @Override
    public void onSetMsgStatus(String status) {
        if ("0".equals(status)) {
            message.setImageResource(R.drawable.xiaoxi);
            return;
        }
        message.setImageResource(R.drawable.xiaoxihong);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R2.id.img_avatar, R2.id.tv_login_tips, R2.id.tv_mobile})
    public void onAvatarClicked() {
        startActivity(new Intent(getActivity(), UserInfoActivity.class));
    }
}
